package logic

import (
	"MyBlogv2/blog-common/HttpCode"
	"MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"context"
	"github.com/jinzhu/copier"

	"MyBlogv2/Servers/UserAction/internal/svc"
	"MyBlogv2/Servers/UserAction/userAction"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserInfoLogic {
	return &GetUserInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetUserInfoLogic) GetUserInfo(in *UserAction.UserActionRequest) (*UserAction.GetUserInfoResponse, error) {
	var user models.UserVo
	var userAccountVo UserAction.UserAccountVo
	userId := in.UserId
	models.Db.Model(new(models.UserVo)).Where("id = ?", userId).First(&user)
	var permissions []string
	models.Db.Model(new(models.UserRole)).
		Table("sys_user_role ur").
		Select("p.permission_key").
		Joins("left join sys_role_permission rp on ur.role_id = rp.role_id").
		Joins("left join sys_permission p on rp.permission_id = p.id").
		Where("ur.user_id = ?", userId).
		Find(&permissions)
	userAccountVo.Permissions = permissions
	var roles []string
	models.Db.Model(new(models.UserRole)).
		Table("sys_user_role ur").
		Select("r.role_key").
		Joins("left join sys_role r on ur.role_id = r.id").
		Where("ur.user_id = ?", userId).
		Find(&roles)
	userAccountVo.Roles = roles

	copier.Copy(&userAccountVo, &user)
	userAccountVo.CreateTime = helper.MyTimeToTimestamp(user.CreateTime)
	userAccountVo.LoginTime = helper.MyTimeToTimestamp(user.LoginTime)
	//TODO 角色，权限
	return &UserAction.GetUserInfoResponse{
		Code: int64(HttpCode.SUCCESS),
		Data: &userAccountVo,
	}, nil
}
